package black_theme.handler.icon;

import black_theme.NodeHandler;
import com.github.sarxos.webcam.Webcam;
import javafx.scene.image.ImageView;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Map;


public class PhotoIcon implements NodeHandler {
    private ImageView photo;
    @Override
    public void handleStyle() {

    }

    @Override
    public void handleEvent() {
        photo.setOnMousePressed(event -> photo.setFitHeight(15));
        photo.setOnMouseReleased(event -> {
            photo.setFitHeight(17);
            new Thread(() -> {
                Webcam webcam = Webcam.getDefault();
                Dimension dimension = new Dimension();
                dimension.setSize(640, 480);
                webcam.setViewSize(dimension);
                webcam.open();
                BufferedImage bufferedImage = webcam.getImage();
                try{
                    Map<String, String> systemData = System.getenv();
                    String savedPath = systemData.get("USERPROFILE") + File.separator + "Desktop" + File.separator + "capture.png";

                    File savedFileOBJ = new File(savedPath);
                    // Delete destination file if it has existed.
                    if(savedFileOBJ.exists()) {
                        savedFileOBJ.delete();
                    }
                    ImageIO.write(bufferedImage, "png", new File(savedPath));
                }catch(IOException ioe){
                    ioe.printStackTrace();
                }
                webcam.close();
            }).start();
        });
    }

    @Override
    public void handleAttributes() {

    }
    public PhotoIcon(ImageView photo) {
        this.photo = photo;
    }
}
